package com.mini.cn.goods.lottery;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;


/**
 * Created by fly on 17/3/29.
 */
public class TurningLottery extends LotteryGo {

    int sum = 0;
    List<Integer> speed;
    HashMap<Integer, Prize> box;

    //构造函数 没有人数限制
    public TurningLottery(List<Prize> prizes) {
        this.prizes = prizes;
        speed = new ArrayList<Integer>();
        box = new HashMap<Integer, Prize>();
        //creatLottoeyBox();
    }

    public TurningLottery() {
        speed = new ArrayList<Integer>();
        box = new HashMap<Integer, Prize>();
    }


    @Override
    public void creatLottoeyBox() {
        int pos = 0;
        if (prizes != null && prizes.size() > 0) {
            speed.clear();
            box.clear();
            //检测合法性
            for (int i = 0; i < prizes.size(); i++) {
                Prize prize = prizes.get(i);
                if (prize.poll < 1) {
                    return;
                }
                sum += prize.poll;
            }
            for (int i = 0; i < sum; i++) {
                speed.add(i);
            }
            for (int i = 0; i < prizes.size(); i++) {
                Prize prize = prizes.get(i);
                for (int c = 0; c < prize.poll; c++) //权重越大所占的面积份数就越多
                {
                    pos = ThreadLocalRandom.current().nextInt(speed.size()); //取随机种子坐标
                    box.put(speed.get(pos), prize);//乱序 礼品放入索引是speed[pos]的箱子里面
                    speed.remove(pos); //移除已抽取的箱子索引号
                }
            }
        }
    }

    @Override
    public Prize LotteryPrize() {
        System.out.println("prize size=" + prizes.size());
        if (prizes.size() == 1) {
            return prizes.get(0);
        }
        System.out.println("box size="+box.size()+"  sum="+sum);
        if (box.size() >= sum) {
            int rand = ThreadLocalRandom.current().nextInt(sum);
            System.out.print("sum=" + sum + "  rand=" + rand);
            Prize key = box.get(rand);
            return key;
        }
        return null;
    }

    @Override
    public void clearLotteryBuffer() {
        sum = 0;
        speed.clear();
        box.clear();
        prizes.clear();
        prizes = null;
        speed = null;
        box = null;
    }
}
